from django.utils.deprecation import MiddlewareMixin
from web import models
from django.shortcuts import redirect
from django.conf import settings
import re
import datetime


class Tracer():
    def __init__(self):
        self.user = None
        self.price_policy = None


class AuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
        request.tracer = Tracer()
        user_id = request.session.get('user_id',0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        # 当前用户信息
        request.tracer.user = user_obj
        # 白名单匹配
        for i in settings.WHITE_REGEX_URL_LIST:
            if re.match(i,request.path_info):
                return

        if not request.tracer.user:
            return redirect('login')

        # 登录成功后访问后台的时候获取当前的拥有的额度
        # 方式一：免费额度在交易记录里存储
        # 获取当前用户交易记录ID最大值
        _object = models.Transaction.objects.filter(user=user_obj,status=1).order_by('-id').first()
        print(_object)
        # 判断是否过期
        current_time = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_time:
            _object = models.Transaction.objects.filter(user=user_id,price_policy__category=1).first()
        # 当前用户的价格策略
        request.tracer.price_policy = _object.price_policy